package edu.neepu;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.Test;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainClass {

    String downloadFilePath="D://Image//";

    public static void downImages(String filePath,String imgUrl,String name) throws UnsupportedEncodingException {


        try {
            File files = new File(filePath);
            if (!files.exists()) {
                files.mkdirs();
            }
            //获取下载地址
            URL url = new URL(imgUrl);
            //链接网络地址
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            connection.setConnectTimeout(500000);
            connection.setReadTimeout(500000);
            //获取链接的输出流
            InputStream is = connection.getInputStream();
            //创建文件，fileName为编码之前的文件名
            File file = new File(filePath + name);
            //根据输入流写入文件
            FileOutputStream out = new FileOutputStream(file);
            int i = 0;
            while((i = is.read()) != -1){
                out.write(i);
            }
            out.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test8() throws IOException {

        for (int i = 1; i < 11; i++) {
            Document document = Jsoup.connect("https://bing.ioliu.cn/?p=" + i).get();
            Elements elements = document.select(".item");
            for (Element element : elements) {
                Elements a = element.select(".download");
                System.out.println("下载网址："+a.attr("abs:href"));
                System.out.println("图片下载开始:"+a.attr("abs:href"));
                Elements time = element.select(".calendar");
                Elements location = element.select(".location");
                downImages(downloadFilePath,a.attr("abs:href"),time.text()+" "+location.text()+".jpg");
                System.out.println("下载完毕！");
            }

        }
    }
}
